package com.yuyou.fn.wx.config;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * Created by wens on 2017/3/7.
 */
public class WxMpInRedisConfigStorage extends WxMpInMemoryConfigStorage {

    private static final String WX_ACCESS_TOKEN_KEY = "WX_ACCESS_TOKEN_KEY";

    private RedisTemplate template;

    public WxMpInRedisConfigStorage(RedisTemplate template) {
        this.template = template;
    }

    @Override
    public boolean isAccessTokenExpired() {
        return template.getExpire(WX_ACCESS_TOKEN_KEY) <= 0;
    }

    @Override
    public void expireAccessToken() {
        template.expireAt(WX_ACCESS_TOKEN_KEY, new Date());
    }

    @Override
    public String getAccessToken() {
        return (String) template.opsForValue().get(WX_ACCESS_TOKEN_KEY);
    }

    @Override
    public Lock getAccessTokenLock() {
        return super.getAccessTokenLock();
    }

    @Override
    public void setAccessToken(String accessToken) {
        super.setAccessToken(accessToken);
    }


    @Override
    public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
        super.updateAccessToken(accessToken, expiresInSeconds);
        template.opsForValue().set(WX_ACCESS_TOKEN_KEY, accessToken, expiresInSeconds, TimeUnit.SECONDS);
    }
}
